package com.summer.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.summer.mall.common.Const;
import com.summer.mall.common.ResponseService;
import com.summer.mall.entity.*;
import com.summer.mall.mapper.*;
import com.summer.mall.service.OrderService;
import com.summer.mall.util.BigDecimalUtil;
import com.summer.mall.util.DateTimeUtil;
import com.summer.mall.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.smartcardio.CardTerminal;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("orderService")
public class OrderServiceImpl implements OrderService{


    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShippingMapper shippingMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    public ResponseService createOrder(Integer userId, Integer shippingId) {
        List<Cart> cartList = cartMapper.selectCheckedCartByUserId(userId);

        ResponseService cartOrderItemList = this.getCartOrderItemList(userId, cartList);
        System.out.println(cartOrderItemList.getData().toString());
        if (cartOrderItemList.isSuccess()) {
            return cartOrderItemList;
        }

        List<OrderItem> orderItemList = (List<OrderItem>) cartOrderItemList.getData();
        System.out.println(orderItemList.get(0).getProductId());
        if (CollectionUtils.isEmpty(orderItemList)) {
            return ResponseService.createByErrorMessage("购物车为空");
        }

        //计算总价
        BigDecimal payment = this.getTotalPrice(orderItemList);

        //生成订单
        //组装订单对象
        Order order = this.assembleOrder(userId, shippingId, payment);
        System.out.println(order);
        if (order == null) {
            return ResponseService.createByErrorMessage("生成订单错误");
        }
        System.out.println(order.getShippingId());
        //同一个订单的订单条目，设置订单号
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderNo(order.getOrderNo());
        }
        //批量插入到order_item
        orderItemMapper.batchInsert(orderItemList);

        //减库存
        this.reduceProductStock(orderItemList);
        //清空购物车
        this.clearCart(cartList);

        //返回前端，格式转换 生成 Vo
        OrderVo orderVo = this.assembleOrderVo(order, orderItemList);


        return ResponseService.createBySuccess(orderVo);
    }

    /**
    * @Author : complone
    * @Param 当前用户ID
    * @Param 订单编号
    * @Return 返回取消后的订单状态
    * @Desrcption: 取消订单
    * @Date  10:58
     **/
    @Override
    public ResponseService<String> cancel(Integer userId, Long orderNo) {
        Order order = orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        System.out.println(order.getId()+": --------- :"+order.getStatus());
        if (order == null){
           return ResponseService.createByErrorMessage("该用户此订单不存在");
        }
        if (order.getStatus()!=Const.OrderStatusEnum.NO_PAY.getCode()){
            return ResponseService.createByErrorMessage("已付款，无法取消订单");
        }

        Order updateOrder = new Order();
        updateOrder.setId(order.getId());
        updateOrder.setStatus(Const.OrderStatusEnum.CANCEL.getCode());

        int rowCount = orderMapper.updateByPrimaryKeySelective(updateOrder);
        if (rowCount>0){
            return ResponseService.createBySuccessMessage("用户已取消订单");
        }
        return ResponseService.createByErrorMessage("用户取消订单失败");
    }

    /**
     * 获取订单列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseService<PageInfo> manageList(int pageNum, int pageSize) {
        List<ManagerOrderVo> managerOrderVos = new ArrayList<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orders = orderMapper.selectAllOrder();
        for(int i = 0; i < orders.size();i++) {
            ManagerOrderVo managerOrderVo = assembleOrderListVo(orders.get(i));
            managerOrderVos.add(managerOrderVo);
        }
        PageInfo pageResult = new PageInfo(orders);
        pageResult.setList(managerOrderVos);

        return ResponseService.createBySuccess(pageResult);
    }

    /**
     * 获取指定订单信息
     * @param orderNo
     * @return
     */
    @Override
    public ResponseService<ManagerOrderVo> manageDetail(Long orderNo) {
        if(orderNo == null){
            return ResponseService.createByErrorMessage("该订单不存在！");
        }
        Order order = orderMapper.selectByOrderNo(orderNo);
        ManagerOrderVo managerOrderVo = assembleOrderListVo(order);
        return ResponseService.createBySuccess(managerOrderVo);
    }


    /**
     * 搜索指定的订单信息
     * @param orderNo
     * @return
     */
    @Override
    public ResponseService<PageInfo> manageSearch(Long orderNo) {
        if(orderNo == null){
            return ResponseService.createByErrorMessage("该订单不存在！");
        }
        List<Order> orders = orderMapper.selectListByOrderNo(orderNo);
        List<ManagerOrderVo> managerOrderVos = new ArrayList<>();
        for(int i = 0; i < orders.size();i++){
            ManagerOrderVo  managerOrderVo = assembleOrderListVo(orders.get(i));
            managerOrderVos.add(managerOrderVo);
        }
        PageInfo pageResult = new PageInfo(managerOrderVos);
        pageResult.setList(managerOrderVos);
        return ResponseService.createBySuccess(pageResult);
    }

    /**
     * 发货
     * @param orderNo
     * @return
     */
    @Override
    public ResponseService<String> manageSendGoods(Long orderNo) {
        int flag = orderMapper.updateByOrderNo(orderNo);
        if(flag > 0){
            return ResponseService.createBySuccess("更新成功过!");
        }
        return ResponseService.createByErrorMessage("更新失败!");
    }

    /**
     * 订单结果组装
     * @param order
     * @return
     */
    private ManagerOrderVo assembleOrderListVo(Order order) {
        ManagerOrderVo managerOrderVo= new ManagerOrderVo();
        managerOrderVo.setOrderNo(order.getOrderNo());
        managerOrderVo.setStatus(order.getStatus());
        managerOrderVo.setPayment(order.getPayment());
        managerOrderVo.setPaymentType(order.getPaymentType());
        managerOrderVo.setPostage(order.getPostage());
        managerOrderVo.setPaymentTime(order.getPaymentTime());
        managerOrderVo.setSendTime(order.getSendTime());
        managerOrderVo.setEndTime(order.getEndTime());
        managerOrderVo.setCreateTime(order.getCreateTime());
        managerOrderVo.setCloseTime(order.getCloseTime());
        return managerOrderVo;
    }

    /**
    * @Author : complone
    * @Desrcption: 用户支付接口
    * @Date  11:37
     **/
    @Override
    public ResponseService pay(Long orderNo, Integer userId) {
        Order order = orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        if (order == null){
            return ResponseService.createByErrorMessage("用户没有该订单");
        }

        List<OrderItem> orderItemList = orderItemMapper.getByOrderNoUserId(orderNo, userId);

        if (orderItemList == null){
            return ResponseService.createByErrorMessage("订单信息为空,查询失败");
        }

        //订单状态
        if (order.getStatus() >= Const.OrderStatusEnum.PAID.getCode()) {
            return ResponseService.createByErrorMessage("订单已支付");
        }else {
            order.setStatus(Const.OrderStatusEnum.PAID.getCode());
            orderMapper.updateByPrimaryKeySelective(order);
        }

        OrderVo orderVo = this.assembleOrderVo(order,orderItemList);


        return ResponseService.createBySuccess("下单成功",orderVo);

    }

    @Override
    public ResponseService<OrderVo> getOrderDetail(Integer userId, Long orderNo) {
        Order order = orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        if (order != null){
            List<OrderItem> orderItemList = orderItemMapper.getByOrderNoUserId(orderNo,userId);
            OrderVo orderVo = this.assembleOrderVo(order, orderItemList);
            return ResponseService.createBySuccess(orderVo);
        }
        return ResponseService.createByErrorMessage("订单不存在");


    }

    @Override
    public ResponseService<PageInfo> getOrderList(Integer userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList =orderMapper.selectByUserId(userId);
        PageInfo pageInfo = new PageInfo(orderList);

        List<OrderVo> orderVoList = this.assembleOrderVoList(userId,orderList);
        pageInfo.setList(orderVoList);

        return ResponseService.createBySuccess(pageInfo);
    }

    @Override
    public ResponseService getOrderCartProduct(Integer userId) {

        OrderProductVo orderProductVo = new OrderProductVo();
        //从购物车中获取数据

        List<Cart> cartList = cartMapper.selectCheckedCartByUserId(userId);
        ResponseService responseService = this.getCartOrderItemList(userId, cartList);
        if (!responseService.isSuccess()) {
            return responseService;
        }

        List<OrderItem> orderItemList= (List<OrderItem>) responseService.getData();

        List<OrderItemVo> orderItemVoList = Lists.newArrayList();
        BigDecimal payment = new BigDecimal("0.0");
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
            orderItemVoList.add(assembleOrderItemVo(orderItem));
        }
        orderProductVo.setProductTotalPrice(payment);
        orderProductVo.setOrderItemVoList(orderItemVoList);
        orderProductVo.setImageHost(Const.LOCAL_URL);

        return responseService.createBySuccess(orderProductVo);
    }

    @Override
    public ResponseService queryOrderPayStatus(Integer userId, Long orderNo) {

        Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
        if (order==null) {
            return ResponseService.createByErrorMessage("用户没该订单");
        }
        //成功的订单
        if (order.getStatus() >= Const.OrderStatusEnum.PAID.getCode()) {
            return ResponseService.createBySuccess();
        }
        return ResponseService.createByError();
    }

    private ResponseService getCartOrderItem(Integer userId, List<Cart> cartList) {
        List<OrderItem> orderItemList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(cartList)) {
            return ResponseService.createByErrorMessage("购物车为空");
        }
        for (Cart cartItem : cartList) {
            OrderItem orderItem = new OrderItem();
            Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
            if (Const.ProductEnumStatus.ON_SALE.getCode() != product.getStatus()) {
                return ResponseService.createBySuccessMessage("产品" + product.getName() + "不是在售商品");
            }
            if (cartItem.getQuantity() > product.getStock()) {
                return ResponseService.createByErrorMessage("产品" + product.getName() + "库存不足");
            }
            orderItem.setUserId(userId);
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartItem.getQuantity()));
            orderItemList.add(orderItem);
        }
        return ResponseService.createBySuccess(orderItemList);
    }

    private List<OrderVo> assembleOrderVoList(Integer userId,List<Order> orderList) {
        List<OrderVo> orderVoList = Lists.newArrayList();
        for (Order order : orderList) {
            List<OrderItem> orderItemList = Lists.newArrayList();
            if (userId == null) {
                //todo 管理员查询
                orderItemList = orderItemMapper.getByOrderNo(order.getOrderNo());
            }else {
                orderItemList = orderItemMapper.getByOrderNoUserId(order.getOrderNo(),userId);
            }

            OrderVo orderVo = assembleOrderVo(order, orderItemList);
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }


    public ResponseService getCartOrderItemList(Integer userId, List<Cart> cartList) {
        List<OrderItem> orderItemList = Lists.newArrayList();


        if (CollectionUtils.isEmpty(cartList)) {
            return ResponseService.createByErrorMessage("购物车为空");
        }

        //校验购物车的数量，包括产品的状态和数量
        for (Cart cart : cartList) {
            //一个子订单的明细
            OrderItem orderItem = new OrderItem();
            Product product = productMapper.selectByPrimaryKey(cart.getProductId());

            if (Const.ProductEnumStatus.ON_SALE.getCode() != product.getStatus()) {
                return ResponseService.createByErrorMessage("产品" + product.getName() + "不是在售状态");
            }

            //检查库存
            if (cart.getQuantity() > product.getStock()) {
                return ResponseService.createByErrorMessage("产品" + product.getName() + "库存不足");
            }

            orderItem.setUserId(userId);
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cart.getQuantity()));
//            System.out.println(userId);
            orderItemList.add(orderItem);
            System.out.println(orderItemList.get(0).getProductId());
        }
        System.out.println(orderItemList.get(0).getProductId());

        return ResponseService.createBySuccess(orderItemList);
    }

    //组装地址详情Vo
    /**
    * @Author : complone
    * @Desrcption: 组装订单地址
    * @Date  9:43
    **/
    private ShippingVo assembleShippingVo(Shipping shipping) {
        ShippingVo shippingVo = new ShippingVo();
        shippingVo.setReceiverName(shipping.getReceiverName());
        shippingVo.setReceiverAddress(shipping.getReceiverAddress());
        shippingVo.setReceiverProvince(shipping.getReceiverProvince());
        shippingVo.setReceiverCity(shipping.getReceiverCity());
        shippingVo.setReceiverDistrict(shipping.getReceiverDistrict());
        shippingVo.setReceiverMobile(shipping.getReceiverMobile());
        shippingVo.setReceiverZip(shipping.getReceiverZip());
        shippingVo.setReceiverPhone(shippingVo.getReceiverPhone());
        return shippingVo;
    }


    /**
     *组装 OrderVo 对象
     * @param order
     * @param orderItemList
     * @return
     */
    private OrderVo assembleOrderVo(Order order,List<OrderItem> orderItemList){
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setPayment(order.getPayment());
        orderVo.setPaymentType(order.getPaymentType());
        orderVo.setPaymentTypeDesc(Const.PaymentTypeEnum.codeOf(order.getPaymentType()).getValue());

        orderVo.setPostage(order.getPostage());
        orderVo.setStatus(order.getStatus());
        orderVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());

        orderVo.setShippingId(order.getShippingId());
        Shipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
        if(shipping != null){
            orderVo.setReceiverName(shipping.getReceiverName());
            orderVo.setShippingVo(assembleShippingVo(shipping));
        }

        orderVo.setPaymentTime(DateTimeUtil.dateToStr(order.getPaymentTime()));
        orderVo.setSendTime(DateTimeUtil.dateToStr(order.getSendTime()));
        orderVo.setEndTime(DateTimeUtil.dateToStr(order.getEndTime()));
        orderVo.setCreateTime(DateTimeUtil.dateToStr(order.getCreateTime()));
        orderVo.setCloseTime(DateTimeUtil.dateToStr(order.getCloseTime()));

        orderVo.setImageHost(Const.LOCAL_URL);

        List<OrderItemVo> orderItemVoList = Lists.newArrayList();

        for(OrderItem orderItem : orderItemList){
            OrderItemVo orderItemVo = assembleOrderItemVo(orderItem);
            orderItemVoList.add(orderItemVo);
        }
        orderVo.setOrderItemVoList(orderItemVoList);
        return orderVo;
    }


    //订单单条Vo
    private OrderItemVo assembleOrderItemVo(OrderItem orderItem) {
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setOrderNo(orderItem.getOrderNo());
        orderItemVo.setProductId(orderItem.getProductId());
        orderItemVo.setProductName(orderItem.getProductName());
        orderItemVo.setProductImage(orderItem.getProductImage());
        orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
        orderItemVo.setQuantity(orderItem.getQuantity());
        orderItemVo.setTotalPrice(orderItem.getTotalPrice());

        orderItemVo.setCreateTime(DateTimeUtil.dateToStr(orderItem.getCreateTime()));
        return orderItemVo;
    }

    //组装订单对象
    private Order assembleOrder(Integer userId, Integer shippingId, BigDecimal payment) {
        Order order = new Order();
        long orderNo = this.generateOrderNo();
        order.setOrderNo(orderNo);
        order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
        order.setPostage(0);
        order.setPaymentType(Const.PaymentTypeEnum.ONLINE_PAY.getCode());
        order.setPayment(payment);
        order.setUserId(userId);
        order.setShippingId(shippingId);

        //todo 创建订单时还没有发货和付款等信息

        int rowCount = orderMapper.insert(order);
        if (rowCount>0) {
            return order;
        }

        return null;
    }

    /**
     * 生成订单号
     * fixme 此处以后要扩展,采用分布式订单号生成策咯
     * @return
     */
    private long generateOrderNo() {
        long currentTime = System.currentTimeMillis();
        return currentTime + new Random().nextInt(100);
    }

    private BigDecimal getTotalPrice(List<OrderItem> orderItemList) {
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
        }
        return payment;
    }


    //清空购物车
    private void clearCart(List<Cart> cartList) {
        for (Cart cart : cartList) {
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
    }

    //减少库存
    private void reduceProductStock(List<OrderItem> orderItemList) {
        for (OrderItem orderItem : orderItemList) {
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            product.setStock(product.getStock() - orderItem.getQuantity());
            productMapper.updateByPrimaryKeySelective(product);
        }
    }

    @Override
    public void closeOrder(Integer hour) {
       

    }
}
